var PublicPostHandler = function () {
}

PublicPostHandler.prototype.initEditor = function () {
    let csrf_token = $('meta[name="csrf-token"]').attr('content');
    let editor = new window.wangEditor('#editor')
    editor.config.uploadImgServer = '/post/image/upload'
    editor.config.uploadFileName = 'image'
    // 1.放到请求体中
    // 2.放到请求头中X-CSRFToken
    // 在与cookie中的csrf_token一致的情况下，才能通过
    editor.config.uploadImgHeaders = {
        'X-CSRFToken': csrf_token
    }
    editor.config.uploadImgMaxSize = 1024 * 1024 * 5
    editor.create()
    this.editor = editor
}



PublicPostHandler.prototype.listenSubmitEvent = function () {
    let that = this
    $("#submit-btn").on('click', function (event) {
        event.preventDefault()
        let content = that.editor.txt.html()
        let title = $("input[name='title']").val()
        let board_id = $("select[name='board_id']").val()
        zlajax.post({
            'url': '/post/public/',
            'data': {
                'title': title,
                'content': content,
                'board_id': board_id
            },
            'success': function (data) {
                if (data['code'] === 200) {
                    let post_id = data['data']['id']
                    window.location = '/post/detail/' + post_id
                } else {
                    alert(data['message'])
                }
            }
        })
    })
}

PublicPostHandler.prototype.run = function () {
    this.initEditor();
    this.listenSubmitEvent();
}

$(function () {
    var handler = new PublicPostHandler();
    handler.run();
});